package org.doxla.oomwatch.observerable.mail;

import java.util.Observable;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.doxla.oomwatch.observerable.AbstractOomWatcher;
import org.doxla.oomwatch.observerable.OomObserver;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;

/**
 * Sends a mail notification when the Observer is updated by the
 * Observerable it is registered to.
 * 
 * @author danoxlade
 *
 */
public class MailNotificationObserver implements OomObserver {

	private static final String THRESHOLD_REPLACER = "[[THRESHOLD]]";
	private static final String CURRENT_MEM_REPLACER = "[[CURRENT_MEM]]";


	private JavaMailSender mailSender = null;
	
	/**
	 * Email properties
	 */
	private String recipient = null;
	private String sender = null;
	private String body = null;
	private String subject = null;

	public MailNotificationObserver(JavaMailSender mailSender,String recipient,String sender, String body, String subject){
		super();
		this.mailSender = mailSender;
		this.recipient = recipient;
		this.sender = sender;
		this.body = body;
		this.subject = subject;
	}

	public void update(Observable o, Object arg) {
		AbstractOomWatcher watcher = (AbstractOomWatcher) o;
		sendNotificationEmail(watcher.getThreshold());
	}

	private void sendNotificationEmail(final long thresholdExceeded) {
		MimeMessagePreparator preparator = new MimeMessagePreparator() {

			public void prepare(MimeMessage mimeMessage) throws Exception {
				createMessage(mimeMessage,thresholdExceeded);
			}
		};
		this.mailSender.send(preparator);
	}

	private void createMessage(MimeMessage mimeMessage, long thresholdExceeded) throws MessagingException {
		MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
		message.setTo(recipient);
		message.setSubject(subject );
		message.setFrom(sender);
		message.setText(replaceVars(body,thresholdExceeded));
		message.setValidateAddresses(true);
	}

	/**
	 * TODO refactor to make this nicer
	 * 
	 * @param body2
	 * @param thresholdExceeded
	 * @return
	 */
	private String replaceVars(String body2, long thresholdExceeded) {
		String toReturn = body2.replaceAll(THRESHOLD_REPLACER, String.valueOf(thresholdExceeded));
		toReturn = toReturn.replaceAll(CURRENT_MEM_REPLACER,
								String.valueOf(Runtime.getRuntime().totalMemory()));
		
		return toReturn;
	}

}
